package org.nokatag.system;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nokatag.password.AESPlus;


/**
 * 文件上传
 * @author rebin
 *
 */
public class FileUpload {
	private HttpServletResponse response;
	private FilterConfig config;
	
	public void FileUtil(HttpServletRequest request,HttpServletResponse response,FilterConfig config,String msg){
		this.response = response;
		this.config = config;
		String dotype = request.getParameter("do");
		if(dotype.equalsIgnoreCase("add")){
			String fileid = Upload(request);//上传
			try{
				String reid = request.getParameter("reid");
				if("Y".equalsIgnoreCase(reid)){
					String rmsg = (null==msg?fileid:String.format(msg,fileid));
					response.getOutputStream().write(rmsg.getBytes());
				}else{
					String rmsg = (null==msg?"1":String.format(msg,"1"));
					response.getOutputStream().write(rmsg.getBytes());
				}
			}catch(Exception se){
				se.printStackTrace();
			}
		}else if (dotype.equalsIgnoreCase("dell")){
			dellfile(request);//删除
		}else if (dotype.equalsIgnoreCase("get")){
			getfile(request);//下载
		}else if (dotype.equalsIgnoreCase("red")){
			readfile(request);//读取
		}else if (dotype.equalsIgnoreCase("info")){
			fileinfo(request);//获取信息
		}else{
			filetable(request);//文件列表
		}
		
	}
	
	public void FileUtil(HttpServletRequest request,HttpServletResponse response,FilterConfig config){
		this.response = response;
		this.config = config;
		
		String dotype = request.getParameter("do");
		if(dotype.equalsIgnoreCase("add")){
			String fileid = Upload(request);//上传
			try{
				String reid = request.getParameter("reid");
				if(null!=fileid){
					if("Y".equalsIgnoreCase(reid)){
						response.getOutputStream().write(fileid.getBytes());
					}else{
						response.getOutputStream().write("1".getBytes());
					}
				}else{
					response.sendError(901);//上传失败
					response.getOutputStream().write("0".getBytes());
				}
			}catch(Exception se){
				se.printStackTrace();
			}
		}else if (dotype.equalsIgnoreCase("dell")){
			dellfile(request);//删除
		}else if (dotype.equalsIgnoreCase("get")){
			getfile(request);//下载
		}else if (dotype.equalsIgnoreCase("red")){
			readfile(request);//读取
		}else if (dotype.equalsIgnoreCase("info")){
			fileinfo(request);//获取信息
		}else{
			filetable(request);//文件列表
		}
		
	}
	//----------------上传------------------------------
	public String Upload(HttpServletRequest request){
		Long filisdsn =System.nanoTime();//时间值
		SmartUpload mySmartUpload = new SmartUpload();
        try{
            mySmartUpload.initialize(config,request,response);
            mySmartUpload.upload();
            for (int i=0;i<mySmartUpload.getFiles().getCount();i++){
            SmartFile file = mySmartUpload.getFiles().getFile(i);
            String queryString = URLDecoder.decode(request.getQueryString(),Concest.ENCODING);
            file.setFileName(Unescape.unescapestr(Function.requestQueryString(queryString,"fln")));
            String sessionid = Function.requestQueryString(queryString,"sessionid");//request.getParameter("sessionid");
            String type = Function.requestQueryString(queryString,"type");//request.getParameter("type");
            String text=Unescape.unescapestr(Function.requestQueryString(queryString,"text"));
            text=text.replace("\n", "").replace("\t", "").replace("\r", "");
            
            if (file.isMissing()) continue;
             String filename = file.getFileName();
             //------------全局文件过滤------------------
             Boolean isUp=false;
             if(Concest.UPDOCTYPE!=null && !Concest.UPDOCTYPE.isEmpty()){
	             for(String doctype:Concest.UPDOCTYPE){
	            	 if(doctype.equals("*")){//所有文件类型
	            		 isUp=true;//在允许上传的文件类型
	            		 break;
	            	 }
	            	 if(filename.substring(filename.lastIndexOf(".")+1,filename.length()).equalsIgnoreCase(doctype)){
	            		 isUp=true;//在允许上传的文件类型
	            	 }
	             }
             }
             //-----------------------------------
             if(isUp){
	             Map<String,String> map = new HashMap<String,String>();
	             map.put(Concest.UP_FILEID, String.valueOf(filisdsn));
	             map.put(Concest.UP_FILENAME, filename);
	             map.put(Concest.UP_FILECREATEDATE, Function.NewDate("yyyy-MM-dd kk:mm:ss"));
	             map.put(Concest.UP_FILEPATH, filisdsn+"/" + filename);
	             map.put(Concest.UP_FILETYPE, file.getFileExt().toLowerCase());
	             map.put(Concest.UP_FILEJSPTIMEID, sessionid);
	             map.put(Concest.UP_FILESELECTTYPE, type);
	             map.put(Concest.UP_FILEFTEXT, text);
	             FileUploadSaveInterface futil =getFileUploadSaveInterface();//保存文件
	             String autofileName = map.get(Concest.UP_FILEID)+"_"+AESPlus.encrypt(map.get(Concest.UP_FILEJSPTIMEID),Concest.SQLKEY)+Concest.UP_FILEEXT;//文件名
	             map.put(Concest.UP_FILENAME_COPY, autofileName);//自动生成的文件副本
	             String filepath =futil.upload(file.getFileInput(), map);
	             if(null==filepath){
	            	 return null;
	             }
	             map.put(Concest.UP_FILE_PATH, filepath);
	             if(!FileUploadDBSQL.saveAsNoka(map)){//保存文件记录
	            	return null;
	             }else{
	            	return String.valueOf(filisdsn);
	            }
	          }
            }
        }catch(Exception e){
            BugInfoWrint.Print(e);
        }
        return null;
	}
	//-------------------删除-------------------------------------
	public void dellfile(HttpServletRequest request){
		try {
			String[] fileids = request.getParameterValues("fileids");
			if(fileids!=null){
				List<String> filsList =FileUploadDBSQL.delAsNoka(fileids);//删除数据库记录
				FileUploadSaveInterface futil =getFileUploadSaveInterface();
				for(String filePath:filsList){
					futil.delFile(filePath);//删除文件
				}
			}
		} catch (Exception e) {
			BugInfoWrint.Print(e);
		}
		try {
			response.sendRedirect(request.getAttribute("rootpath").toString()+"/nokatag/file/upload/dbtable.html?rel=1");
		} catch (Exception e) {
			BugInfoWrint.Print(e);
		}
	}
	//---------------------下载------------------------------------
	public void getfile(HttpServletRequest request){
		try {
			SmartUpload su = new SmartUpload();
			su.initialize(config,request,response);
			su.setContentDisposition(null);
			//--------------------------------------------------
			FileItem fileItem=FileUploadDBSQL.ReadFileNoka(request.getParameter("fileid"));
			FileUploadSaveInterface futil= getFileUploadSaveInterface();
			InputStream fi =futil.getFile(fileItem.getFilepath());
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			byte[] bytes = new byte[fi.available()];
			while(fi.read(bytes) != -1) {
				out.write(bytes);
			}
			out.close();
			fi.close();
			su.downloadField(out.toByteArray(), null, fileItem.getFilename());
			//----------------------------------------------------
		} catch (Exception e) {
			BugInfoWrint.Print(request.getParameter("fileid")+e);
		}
	}
	//-------------读取文件----------------------------
	public void readfile(HttpServletRequest request){
		try {
			//------------------------------------------------------------------
			if(FileUploadDBSQL.IsType(request.getParameter("fileid"),request)){
				FileItem fileItem= FileUploadDBSQL.ReadFileNoka(request.getParameter("fileid"));
				FileUploadSaveInterface futil= getFileUploadSaveInterface();
				InputStream input=futil.getFile(fileItem.getFilepath());
				int lent=(input.available()==0?2:input.available());
				String outType = FileUploadDBSQL.getContentType(fileItem.getType());
				if(null!=outType){
					response.setContentType(outType);
				}
				OutputStream out = response.getOutputStream();
				byte[] b = new byte[lent];
				while(input.read(b)!=-1){
					out.write(b);
				}
				out.flush();
				out.close();
				input.close();
			}else{
				getfile(request);//不能显示，就下载 
			}
		} catch (Exception e) {
			 BugInfoWrint.Print(request.getParameter("fileid")+e);
		}
	}
	public void fileinfo(HttpServletRequest request){//获取信息
		try {
			if(request.getParameter("fileid")==null){
				return ;
			}
			String restr=null;
			String basepath=String.valueOf(request.getAttribute("rootpath"));
			String resourcePath = RequestUtils.getServletPath(request);
			restr=FileUploadDBSQL.fileidToFileNames(resourcePath,request.getParameter("fileid"),Integer.parseInt(request.getParameter("sh")),request.getParameter("s"),request.getParameter("e"),basepath,request);
			if(restr!=null){
				OutputStream out = response.getOutputStream();
				Writer wr=new OutputStreamWriter(out,Concest.ENCODING);
				wr.write(restr);
				wr.flush();
				out.flush();
				wr.close();
				out.close();
			}
		} catch (Exception e) {
			 BugInfoWrint.Print(request.getParameter("fileid")+e);
		}
		
	}
	public static String filetable(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		String sessionid = request.getParameter("sessionid");
		String exit = request.getParameter("filetypeextension");
		String type = request.getParameter("type");//uid,表示按用户自定义id，sid，表示按sessionid, pid 表示按页面
		String fvalue = request.getParameter("fvalue");//当前控件的值
		String idreadio = request.getParameter("idreadio");//是否单选
		
		String basepath=String.valueOf(request.getAttribute("rootpath"));
		if(sessionid!=null){
			String uid = sessionid.split(",")[0];//用户自定义id
			String sid = sessionid.split(",")[1];//sessionid
			String pid = sessionid.split(",")[2];//页面id
			boolean tnr=true;
			//---------------------------------------------------------------
			List<Map<String,String>> fm=null;
			FileUploadDBSQL.CeeateFileTable();//检查表是否存在
			fm=FileUploadDBSQL.fileHead(Concest.FILESERVERPATH,exit,type,fvalue,sessionid,request);
			
			if(fm!=null){
			for(Map<String,String> map:fm){
				try{
					if(type.equalsIgnoreCase("uid") && map.get("jsptimeid").split(",")[0].equalsIgnoreCase(uid) && tnr){
						sb.append("<tr onclick=\"rowclick('"+map.get("fileid")+"','"+map.get("filetype")+"');\" id=\"rows_color_"+map.get(Concest.UP_FILEID)+"\"><td  style=\"width:35px;\" class=\"file_upload_data_table_td\"><input name=\"fileids\" id=\"fileids\" checked=\"checked\" type=\""+("true".equals(idreadio)?"radio":"checkbox")+"\" value=\""+map.get("fileid")+"\"/></td><td style=\"width:195px;\" class=\"file_upload_data_table_td\">"+formatName(basepath,map.get("fileid"),map.get("filename"))+"</td><td style=\"width:40px;\" class=\"file_upload_data_table_td\">"+map.get("filetype")+"</td><td style=\"width:130px;\" class=\"file_upload_data_table_td\">"+map.get("filecreatedate")+"</td><td style=\"display: none;width: 0px;\">"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						if(null!=map.get(Concest.UP_FILEFTEXT) && map.get(Concest.UP_FILEFTEXT).trim().length()>0){
							sb.append("<tr><td class=\"file_upload_data_table_td\" colspan=\"5\" >"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						}
					}else if(type.equalsIgnoreCase("sid") && map.get("jsptimeid").split(",")[1].equalsIgnoreCase(sid) && tnr){
						sb.append("<tr onclick=\"rowclick('"+map.get("fileid")+"','"+map.get("filetype")+"');\" id=\"rows_color_"+map.get(Concest.UP_FILEID)+"\"><td  style=\"width:35px;\" class=\"file_upload_data_table_td\"><input name=\"fileids\" id=\"fileids\" checked=\"checked\" type=\""+("true".equals(idreadio)?"radio":"checkbox")+"\" value=\""+map.get("fileid")+"\"/></td><td style=\"width:195px;\" class=\"file_upload_data_table_td\">"+formatName(basepath,map.get("fileid"),map.get("filename"))+"</td><td style=\"width:40px;\" class=\"file_upload_data_table_td\">"+map.get("filetype")+"</td><td style=\"width:130px;\"  class=\"file_upload_data_table_td\">"+map.get("filecreatedate")+"</td><td style=\"display: none;width: 0px;\">"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						if(null!=map.get(Concest.UP_FILEFTEXT) && map.get(Concest.UP_FILEFTEXT).trim().length()>0){
							sb.append("<tr><td class=\"file_upload_data_table_td\"  colspan=\"5\" >"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						}
					}else if(type.equalsIgnoreCase("pid") && map.get("jsptimeid").split(",")[2].equalsIgnoreCase(pid) && tnr){
						sb.append("<tr onclick=\"rowclick('"+map.get("fileid")+"','"+map.get("filetype")+"');\" id=\"rows_color_"+map.get(Concest.UP_FILEID)+"\"><td  style=\"width:35px;\" class=\"file_upload_data_table_td\"><input name=\"fileids\" id=\"fileids\"  checked=\"checked\" type=\""+("true".equals(idreadio)?"radio":"checkbox")+"\" value=\""+map.get("fileid")+"\"/></td><td style=\"width:195px;\" class=\"file_upload_data_table_td\">"+formatName(basepath,map.get("fileid"),map.get("filename"))+"</td><td style=\"width:40px;\" class=\"file_upload_data_table_td\">"+map.get("filetype")+"</td><td style=\"width:130px;\"  class=\"file_upload_data_table_td\">"+map.get("filecreatedate")+"</td><td style=\"display: none;width: 0px;\">"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						if(null!=map.get(Concest.UP_FILEFTEXT) && map.get(Concest.UP_FILEFTEXT).trim().length()>0){
							sb.append("<tr><td class=\"file_upload_data_table_td\"  colspan=\"5\" >"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						}
					}else if((","+fvalue+",").indexOf((","+map.get("fileid")+","))!=-1){
						sb.append("<tr onclick=\"rowclick('"+map.get("fileid")+"','"+map.get("filetype")+"');\" id=\"rows_color_"+map.get(Concest.UP_FILEID)+"\"><td  style=\"width:35px;\" class=\"file_upload_data_table_td\"><input name=\"fileids\" id=\"fileids\"  checked=\"checked\" type=\""+("true".equals(idreadio)?"radio":"checkbox")+"\" value=\""+map.get("fileid")+"\"/></td><td style=\"width:195px;\" class=\"file_upload_data_table_td\">"+formatName(basepath,map.get("fileid"),map.get("filename"))+"</td><td style=\"width:40px;\" class=\"file_upload_data_table_td\">"+map.get("filetype")+"</td><td style=\"width:130px;\"  class=\"file_upload_data_table_td\">"+map.get("filecreatedate")+"</td><td style=\"display: none;width: 0px;\">"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						if(null!=map.get(Concest.UP_FILEFTEXT) && map.get(Concest.UP_FILEFTEXT).trim().length()>0){
							sb.append("<tr><td class=\"file_upload_data_table_td\"  colspan=\"5\" >"+map.get(Concest.UP_FILEFTEXT)+"</td></tr>\n");
						}
					}
				}catch(Exception se){
					se.printStackTrace();
				}
			  }
			}
			//---------------------------------------------------------------
			if(sb.length()>2)
				sb.delete(sb.length()-1,sb.length());
		}
		return sb.toString();
	}
	/**
	 * <p>@Description 格式化文件名称</p>
	 * <p>author rebin </p>
	 * <p>@Time 上午8:35:27</p>
	 * <p>xiefangjian@163.com</p>
	 * @param name
	 * @return
	 */
	private static String formatName (String rootpath,String fileid,String name){
		StringBuffer sb = new StringBuffer();
		sb.append("<div style=\"width:195px;display:block;white-space:nowrap; overflow:hidden; text-overflow:ellipsis;\"><a target=\"_black\" title=\"\" href=\""+rootpath+"/nokatag/nokatag_uploadfile/filefile_id.fs?");
		sb.append("do=red");
		sb.append("&fileid="+fileid+"\">");
		sb.append(name);
		sb.append("</a></div>");
		return sb.toString();
	}

	public static String subStringCN(final String str, final int maxLength) {
		if (str == null) {
			return str;
		}
		String suffix = "...";
		int suffixLen = suffix.length();

		final StringBuffer sbuffer = new StringBuffer();
		final char[] chr = str.trim().toCharArray();
		int len = 0;
		for (int i = 0; i < chr.length; i++) {

			if (chr[i] >= 0xa1) {
				len += 2;
			} else {
				len++;
			}
		}

		if (len <= maxLength) {
			return str;
		}

		len = 0;
		for (int i = 0; i < chr.length; i++) {

			if (chr[i] >= 0xa1) {
				len += 2;
				if (len + suffixLen > maxLength) {
					break;
				} else {
					sbuffer.append(chr[i]);
				}
			} else {
				len++;
				if (len + suffixLen > maxLength) {
					break;
				} else {
					sbuffer.append(chr[i]);
				}
			}
		}
		sbuffer.append(suffix);
		return sbuffer.toString();
	}
	/**
	 * 文件流程处理对象
	 * @param path
	 * @return
	 */
	public  FileUploadSaveInterface getFileUploadSaveInterface(){
		try{
			NLoadFun nloadfun = new NLoadFun();
			return (FileUploadSaveInterface)nloadfun.getBean(Concest.UP_FILE_INPUT_URIL);
		}catch(Exception se){
		}
		return null;
	}
	
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	public FilterConfig getConfig() {
		return config;
	}
	public void setConfig(FilterConfig config) {
		this.config = config;
	}
}


